#!/bin/bash

set -e
set -x

bypy download redis-7.0.15.tar.gz

iplist_path=config
master_ip=$(grep master $iplist_path | awk -F, '{printf $2}')
while read -r line
do
    case $line in
        *'#'*)
            continue
        ;;
        *'end'*)
            break
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac
    
    pass="${parts[0]}" 
    address="${parts[1]}"
    hostname="${parts[2]}"
    flag="${parts[3]}"
    
    if [ $address ];then
        sshpass -p$pass scp redis-7.0.15.tar.gz $address:/opt/
        sshpass -p$pass ssh -n $address tar xf /opt/redis-7.0.15.tar.gz -C /opt
        sshpass -p$pass ssh -n $address 'cd /opt/redis-7.0.15/ && make'
        sshpass -p$pass ssh -n $address 'cd /opt/redis-7.0.15/ && make PREFIX=/usr/local/redis install'
        sshpass -p$pass ssh -n $address mkdir /usr/local/redis/{conf,log,data}
        if [ $flag = "master" ];then
            \cp redis_master.conf.tpl redis_master.conf
            sed -i "s/(local_ip)/$address/" redis_master.conf
            sshpass -p$pass scp redis_master.conf $address:/usr/local/redis/conf/redis.conf
        else
            \cp redis_slave.conf.tpl redis_slave.conf
            sed -i "s/(master_ip)/$master_ip/" redis_slave.conf
            sed -i "s/(local_ip)/$address/" redis_slave.conf
            sshpass -p$pass scp redis_slave.conf $address:/usr/local/redis/conf/redis.conf
        fi
        sshpass -p$pass ssh -n $address useradd -M -s /sbin/nologin redis
        sshpass -p$pass ssh -n $address chown -R redis.redis /usr/local/redis/
        sshpass -p$pass scp redis.service $address:/usr/lib/systemd/system/
        sshpass -p$pass ssh -n $address systemctl daemon-reload
        sshpass -p$pass ssh -n $address systemctl enable --now redis
    fi
    
done < $iplist_path

set +x
set +e